#!/bin/bash 

NODE1_CONFDIR=/tmp/backup_htmf_conf
PATHENV=/usr/local/certificate-services/environment


echo "Welcome to $0, a tool to install Smart Card 2.0"
SetupLogFile="/tmp/smartcard2.0-setup.$$"

runningid=`id -u`
if [ "x${runningid}" != "x0" ] ; then
    echo "must run as root eg: sudo $0"
    exit
fi

if [ -r ${PATHENV} ] ; then
    source ${PATHENV}
else
    echo "${PATHENV} missing"
    exit
fi


randompass() {
    MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    LENGTH="8"
    while [ "${n:=1}" -le "$LENGTH" ] ; do
        PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"
        let n+=1
    done
    echo "$PASS"
}


echo "verbose log messages is redirected to ${SetupLogFile}"
echo "This will make all your issued cards unusable in the new installation since all old CA:s and certificates will be removed"
echo "Enter to continue, ctrl-c to abort"
echo
read a


primecard=n
echo
echo "Will you use PrimeCard as CA Token?"
echo "y/N (default:n) >"
read inputprimecard
if [ "x$inputprimecard" = "xy" -o "x$inputprimecard" = "xY" ] ; then
    primecard=y
fi


mysql=y
echo 
echo "Will you use Mysql as Database layer?"
echo "Y/n (default:y) >"
read inputmysql
if [ "x$inputmysql" != "xn" -o "x$inputmysql" != "xN" ] ; then
    mysql=y



### input ####
    defmysqladminroot=root
    echo
    echo "We'll need your MySQL admin username to setup the database for you?"
    echo -n "mysql-admin-root [${defmysqladminroot}]>"
    read mysqladminroot 
    if [ "x${mysqladminroot}" = "x" ] ; then
	mysqladminroot=${defmysqladminroot}
    fi
    
    defmysqladminpass=
    echo
    echo "We'll need your MySQL admin pass to setup the database for you?"
    echo -n "mysql-admin-pass [${defmysqladminpass}]>"
    read mysqladminpass
    if [ "x${mysqladminpass}" = "x" ] ; then
        mysqladminpass=${defmysqladminpass}
    fi
    
    defmysqlserverhostname=localhost
    echo
    echo "What is the MySQL hostname?"
    echo -n "mysql-serverhostname [${defmysqlserverhostname}]>"
    read mysqlserverhostname
    if [ "x${mysqlserverhostname}" = "x" ] ; then
        mysqlserverhostname=${defmysqlserverhostname}
    fi
    
    defmysqlejbcadbname=ejbca
    echo
    echo "What do you want the ejbca db to be called?"
    echo -n "mysql-ejbca-dbname [${defmysqlejbcadbname}]>"
    read mysqlejbcadbname
    if [ "x${mysqlejbcadbname}" = "x" ] ; then
        mysqlejbcadbname=${defmysqlejbcadbname}
    fi
    
    defmysqlejbcauser=ejbca
    echo
    echo "Select a MySQL ejbca username used to connect to the database from ejbca"
    echo -n "mysql-ejbca-user [${defmysqlejbcauser}]>"
    read mysqlejbcauser
    if [ "x${mysqlejbcauser}" = "x" ] ; then
        mysqlejbcauser=${defmysqlejbcauser}
    fi
    
    mysqlejbcapass=`randompass`
    
fi

defjarsignerpass=foo123
echo
echo "Enter the password for the jarsigner present in the media-bundle directory"
echo "Make sure the key alias is 'jarsigner'!!!"
echo -n "jarsignerpass [${defjarsignerpass}]>"
read jarsignerpass
if [ "x${jarsignerpass}" = "x" ] ; then
    jarsignerpass=${defjarsignerpass}
fi



################## step new jboss ##################

step1InstallNewJboss () {
    echo -n "Step 1/10 Installing a fresh copy of JBoss: "
    /etc/init.d/jboss stop 2>&1 > ${SetupLogFile}
    checkIfJbossIsRunning=`ps -ef | grep java | grep jboss | grep -v grep | awk '{print $2}'`
    if [ "x${checkIfJbossIsRunning}" != "x" ] ; then
	sleep 5 
	checkIfJbossIsRunning=`ps -ef | grep java | grep jboss | grep -v grep | awk '{print $2}'`
	if [ "x${checkIfJbossIsRunning}" != "x" ] ; then
	    kill -9 ${checkIfJbossIsRunning} 
	fi
    fi	
    
    rm -rf ${JBOSS_HOME}                          2>&1 > ${SetupLogFile}
    rm -rf ${JBOSS_DIRNAME}                       2>&1 > ${SetupLogFile}
    unzip ${SC20_DISTFILES}/${JBOSS_DISTNAME}     2>&1 > ${SetupLogFile}
    ln -s  ${JBOSS_DIRNAME} ${JBOSS_HOME} 	  2>&1 > ${SetupLogFile}
    cp ${MYSQLDRIVER} ${JBOSS_HOME}/server/default/lib          2>&1 > ${SetupLogFile}
    for file in ${EXTRA_APPSRV_JARS}/* ; do 
	cp $file ${JBOSS_HOME}/server/default/lib  2>&1 > ${SetupLogFile}
    done
    ${SMARTCARD20_HOME}/jboss-server-switch-log-level.pl INFO 2>&1 > ${SetupLogFile}
    chown -R jboss.jboss ${JBOSS_HOME}            2>&1 > ${SetupLogFile}
    echo "ok"
}


################## step mysql config ##################


step2SetupDatabase () {
    echo -n "Step 2/10 Setting up database: "

    if [ "x$mysql" = "xy" ] ;then
	   #mysql code conf + jar 	
	   #### creating mysql db ####
	
	echo 'show tables' | mysql --user=$mysqladminroot --password=$mysqladminpass $mysqlejbcadbname >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
	    echo
	    echo "database $mysqlejbcadbname does already exist, do you want to start fresh (I'll delete it and add a new ...)?"
	    echo -n "drop-old-db y/n [y]>"
	    read drop
	    if [ "x$drop" = "xy" -o "x$drop" = "xY" -o "x$drop" = "x" ] ; then
		mysqladmin drop --user=$mysqladminroot --password=$mysqladminpass $mysqlejbcadbname 
            else
		echo
		echo "ok, so now you need to sort this manually, then rerun me ( $0 )"
		exit 1
            fi
	    
	fi
	
	mysqladmin create --user=$mysqladminroot --password=$mysqladminpass $mysqlejbcadbname 2>&1 > ${SetupLogFile}
	if [ $? -ne 0 ] ; then
	    echo "failed to create mysql database, you need to do it your self"
	    exit 2	
	fi
	
	#### creating mysql user ####
	
	echo "grant all privileges on ${mysqlejbcadbname}.* to ${mysqlejbcauser}@${mysqlserverhostname} identified by '${mysqlejbcapass}';" | mysql mysql --user=$mysqladminroot --password=$mysqladminpass 2>&1 > ${SetupLogFile}
	if [ $? -ne 0 ] ; then
	    echo "failed to create mysql ejbca user , you need to do it your self"
	    exit 3
	fi
	
	echo "ok"
    fi
}


##############  step setup htmf options #######

step3SetupHtmfOptions () {
    echo -n "Step 3/10 Setting properties in htmf/ejbca: "

	### htmf props
    su -p -s /bin/sh jboss -c "cp ${HTMF_HOME}/hardtokenmgmt.properties.sample ${HTMF_HOME}/hardtokenmgmt.properties "  
    su -p -s /bin/sh jboss -c "perl -pi -e 's/^#build.as.application=true/build.as.application=true/' ${HTMF_HOME}/hardtokenmgmt.properties"
    su -p -s /bin/sh jboss -c "perl -pi -e \"s#^\#customproject.location=.*#customproject.location=${INSTALL_INTO}/${HTMF_CUSTOM_DIRNAME}#\" ${HTMF_HOME}/hardtokenmgmt.properties"
    su -p -s /bin/sh jboss -c "perl -pi -e 's/^jwsdemo.title=Welcome to ToLiMa/jwsdemo.title=Welcome to Smartcard 2.0/' ${HTMF_HOME}/hardtokenmgmt.properties"
#    su -p -s /bin/sh jboss -c "perl -pi -e 's/^#ejbca.ver=3.5/ejbca.ver=3.9/' ${HTMF_HOME}/hardtokenmgmt.properties"
    
    
	### settings for jarsigner
    su -p -s /bin/sh jboss -c "perl -pi -e \"s#^\#jarsigner.keystore=jarsigner.jks#jarsigner.keystore=${HTMF_HOME}/jarsigner.jks#\" ${HTMF_HOME}/hardtokenmgmt.properties"
    su -p -s /bin/sh jboss -c "perl -pi -e 's/^#jarsigner.passphrase=foo123/jarsigner.passphrase=${jarsignerpass}/' ${HTMF_HOME}/hardtokenmgmt.properties"
    


	### mysql conf
    if [ "x$mysql" = "xy" ] ;then
	su -p -s /bin/sh jboss -c "cp ${EJBCA_HOME}/conf/database.properties.sample ${EJBCA_HOME}/conf/database.properties "  
	su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.name=mysql/database.name=mysql/\" ${EJBCA_HOME}/conf/database.properties"
	su -p -s /bin/sh jboss -c "perl -pi -e \"s/#datasource.mapping=mySQL/datasource.mapping=mySQL/\" ${EJBCA_HOME}/conf/database.properties"
	su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.url=jdbc:mysql:\/\/127.0.0.1:3306\/ejbca$/database.url=jdbc:mysql:\/\/127.0.0.1:3306\/${mysqlejbcadbname}/\" ${EJBCA_HOME}/conf/database.properties"
	su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.driver=com.mysql.jdbc.Driver/database.driver=com.mysql.jdbc.Driver/\" ${EJBCA_HOME}/conf/database.properties"
	su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.username=ejbca/database.username=${mysqlejbcauser}/\" ${EJBCA_HOME}/conf/database.properties"
	su -p -s /bin/sh jboss -c "perl -pi -e \"s/#database.password=ejbca/database.password=${mysqlejbcapass}/\" ${EJBCA_HOME}/conf/database.properties"
	
    fi 

    ### ejbca/conf/web.props
        su -p -s /bin/sh jboss -c "cp ${EJBCA_HOME}/conf/web.properties.sample ${EJBCA_HOME}/conf/web.properties "
        su -p -s /bin/sh jboss -c "perl -pi -e \"s/#hardtoken.displaysensitiveinfo=.*/hardtoken.displaysensitiveinfo=false/\" ${EJBCA_HOME}/conf/web.properties"



	### primecard props
    if [ "x$primecard" = "xy" ] ;then
	cd ${PRIMECARD_HOME}/
	./bin/caTokenCard.sh 2>&1 > ${SetupLogFile}
	
		#primecard setting in ejbca.properies
		# hwtoken -> /usr/local/primecard/caTokenClasses-1.6-3.5/
	
	su -p -s /bin/sh jboss -c "cp ${EJBCA_HOME}/conf/ejbca.properties.sample ${EJBCA_HOME}/conf/ejbca.properties"
	su -p -s /bin/sh jboss -c "perl -pi -e 's#^\#hwtoken_classes=../primeCard/caTokenClasses-1.5#hwtoken_classes=/usr/local/primecard/caTokenClasses-1.6-3.5#' ${EJBCA_HOME}/conf/ejbca.properties"
	
	filename=`./bin/changePIN.sh listkeys | grep 'List of keys on card written to file' | perl -ane 'm/List of keys on card written to file\ (.*)\./, print "$1"'`
	mv $filename ${HTMF_HOME}/active-catoken.txt 2>&1 > ${SetupLogFile}
	chown jboss.jboss ${HTMF_HOME}/active-catoken.txt 2>&1 > ${SetupLogFile}
	chmod 644 ${HTMF_HOME}/active-catoken.txt 2>&1 > ${SetupLogFile}
	
    fi # end primecard
    
    rm -f $HTMF_HOME/cacerts/*  2>&1 > ${SetupLogFile}
    
    echo "ok"
}


#### ejbca bootstrap

step4EjbcaBootstrap() {
    echo -n "Step 4/10 Running ejbca bootstrap (prepairing the CA for setup): "
    cd ${EJBCA_HOME}
    
    su -p -s /bin/sh jboss -c "ant bootstrap" 2>&1 > ${SetupLogFile}
    if [ $? -eq 0 ] ; then
	echo "ok"
	rm -f $antbootstrapfile 2>&1 > ${SetupLogFile}
    else
	echo
	echo "FAILED: ant bootstrap failed, see file: ${SetupLogFile} for more info"
	exit 1
    fi
}


#### htmf deploy

step5HtmfDeploy() {
    echo -n "Step 5/10 Running htmf deploy: "
    cd ${HTMF_HOME}
    
    su -p -s /bin/sh jboss -c "ant deploy"  2>&1 > ${SetupLogFile}
    if [ $? -eq 0 ] ; then
       echo "ok"
    else
       echo
       echo "FAILED: htmf ant deplot failed, see file: ${SetupLogFile} for more info"
       exit 1
    fi
}

#### start jboss for the installing

step6StartJboss () {
    echo -n "Step 6/10 Starting jboss: "
    /etc/init.d/jboss start	2>&1 > ${SetupLogFile}
    while true ; do
	sleep 10
	if [ -e ${JBOSS_HOME}/server/default/log/server.log ]; then
	    startedgrep=`grep 'INFO.*Server.*JBoss.*MX MicroKernel.*4.*build: SVNTag=JBoss_.*date=.*Started in' ${JBOSS_HOME}/server/default/log/server.log` 2>&1 > /dev/null
	else
	    sleep 10 # Wait a few more seconds
	    startedgrep=`grep 'INFO.*Server.*JBoss.*MX MicroKernel.*4.*build: SVNTag=JBoss_.*date=.*Started in' ${JBOSS_HOME}/server/default/log/server.log` 2>&1 > /dev/null
	fi
	if [ "x${startedgrep}" != "x" ] ; then
	    break;
	fi
    done	
    echo "ok"

}


######## ejbca:setup ######
step7EjbcaSetup() {
    echo -n "Step 7/10 Running ejbca:setup, Now you will have to answer some questions about this installation: "
    
    cd $HTMF_HOME
    su -p -s /bin/sh jboss -c "ant ejbca:setup" 
    if [ $? -eq 0 ] ; then
	echo "Step ejbca:setup: ok"
    else
	echo
	echo "FAILED: ejbca:setup failed"
	exit 5
    fi
}


###### and ant ######
step8HtmfAntBuild() {
    echo -n "Step 8/10 Running ant  in ${HTMF_HOME}"
    
    if [ -x ${HTMF_HOME}/custom-settings-script.sh ] ; then
	${HTMF_HOME}/custom-settings-script.sh 
    fi
    
    su -p -s /bin/sh jboss -c "cd $HTMF_HOME ; ant"  2>&1 > ${SetupLogFile}
    if [ $? -eq 0 ] ; then
	echo "ok"
    else
	echo
	echo "FAILED: ant in $HTMF_HOME: failed, see file: ${SetupLogFile} for more info"
	exit 6
    fi
}


###### and ant deploy ####
step9HtmfAntDeploy() {
    echo -n "Step 9/10 Running ant deploy in $HTMF_HOME, building the client-app-installer: "
    su -p -s /bin/sh jboss -c "cd $HTMF_HOME ; ant deploy" 2>&1 > ${SetupLogFile}
    if [ $? -eq 0 ] ; then
	echo "ok"
    else
	echo "FAILED: ant deply in $HTMF_HOME: failed, see file: ${SetupLogFile} for more info"
	exit 7
    fi
}


#### restart jboss ####
step10REstartJboss() {
    echo -n "Step 10/10 Restarting Jboss: "
    /etc/init.d/jboss stop 2>&1 > ${SetupLogFile}
    checkIfJbossIsRunning=`ps -ef | grep java | grep jboss | grep -v grep | awk '{print $2}' `
    if [ "x${checkIfJbossIsRunning}" != "x" ] ; then
	sleep 5
	kill -9 ${checkIfJbossIsRunning}
    fi       
    
    sleep  10
    /etc/init.d/jboss start 2>&1 > ${SetupLogFile}
    
    i=0
    while true ; do
	sleep 10
	startedgrep=`grep 'INFO.*Server.*JBoss.*MX MicroKernel.*4.*build: SVNTag=JBoss_.*date=.*Started in' ${JBOSS_HOME}/server/default/log/server.log` 2>&1 > /dev/null
	if [ "x${startedgrep}" != "x" ] ; then
	    break;
	fi
	if [ "x$i" == "x12" ] ; then
	    echo "jboss not started in 120 secs, maybe you're on a slow machine or something went wrong"
	    break;
	fi
    done
    
    echo "ok"
}


stepActivatePrimeCard(){
    
    if [ "x$primecard" = "xy" ] ; then
	echo
	echo "activating the CA:s"
	/usr/local/htmf/src/inst/smartcard20/activate-cas.sh
	echo "to activate CA:s again (after jboss or server restart) run: /usr/local/htmf/src/inst/smartcard20/activate-cas.sh"
	echo 
    fi
    
    echo 
    echo 
    echo "$0 finished"
    echo "now open: https://<hostname>:8442/htmf/isa.jsp to start with the superadmin card"
    echo "then: https://<hostname>:8442/htmf/ to start issuing cards"
    echo 
    echo 
    exit 0
}


step1InstallNewJboss
step2SetupDatabase
step3SetupHtmfOptions
step4EjbcaBootstrap
step5HtmfDeploy
step6StartJboss
step7EjbcaSetup
step8HtmfAntBuild
step9HtmfAntDeploy
step10REstartJboss
stepActivatePrimeCard
